<html>
<head><title>Calculator</title>
</head>

<body>
<h1>Calculator</h1>
<p>v1.0 programmed by Yiqi Yu and Hongxiang Gu <br /></p>
<p>Type an expression in the following box (e.g., 10.5+20*3/25).<br /></p>
<p>
<form method= "POST" action="calculator.php">
		<input type="text" name="equation">
		<input type="submit" value="Calculate">
</form>
</p>
<ul>
<li>Only numbers and +,-,* and / operators are allowed in the expression.
<li>The evaluation follows the standard operator precedence.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>

Here are some(but not limit to) reasonable test cases:

<ol>
  <li> A basic arithmetic operation:  3+4*5=23 </li>
  <li> An expression with floating point or negative sign : -3.2+2*4-1/3 = 4.46666666667, 3+-2.1*2 = -1.2 </li>
  <li> Some typos inside operation (e.g. alphabetic letter): Invalid input expression 2d4+1 </li>
</ol>

<?php
		$subject = $_POST["equation"];

		$pattern = "/^\s*(([\-]?\d+[\.]?\d*)([\+\-\*\/][\-]?\d+[\.]?\d*)*)\s*$/";

		//if empty input or input with only whitespaces, do nothing
		if(preg_match('/^\s*$/', $subject)){}
		//if matches the pattern of basic calculation, proceed
		elseif(preg_match($pattern, $subject))
		{
			if((preg_match("/\/0+([\+\-\*\/])/", $subject))
			 ||(preg_match("/\/0+$/", $subject))
			 ||(preg_match("/\/(\s*0*\s*)\.(\s*0*\s*)+[^(\d)]/", $subject))
			 ||(preg_match("/\/(\s*0*\s*)*\.(\s*0*\s*)+$/", $subject)))
			 //dealing with various situations of division of zero,outputs nothing
			 {
				 $answer="";
				 print ('<h2>'.Result.'</h2>');
				 print($subject." = ".$answer);
			 }
			 //use eval() to do the operations
			 else
			 {
				 $return=eval("\$answer= $subject;") ;
				 //if eval() returns 0, then output error message. 
				 //however, I didn't meet this situation when debugging
				 if($return===FALSE){
					print '<h2>'.Result.'</h2>';
					print ("Invalid input expression");
				 }
				 print '<h2>'.Result.'</h2>';
				 print($subject." = ".$answer);
			 }
		}else{
			print '<h2>'.Result.'</h2>';
			print ("Invalid input expression ".$subject);
		}
?>

</body>
</html>



